﻿/*
 * @author Lee 
 * Time: 20180403 
 * Abstract: SharePoint API的二次封装
 */
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security;
using System.Security.Cryptography.X509Certificates;

namespace SharePointHelper.DLL.CSOM
{
    public class Security
    {
        #region 设置认证信息
        /// <summary>
        /// 设置online认证信息
        /// </summary>
        /// <param name="clientContext"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        public static void setOnlineCredential(ClientContext clientContext,string userName,string password)
        {
            //set the user name and password
            SecureString secureString = new SecureString();
            foreach (char c in password.ToCharArray())
            {
                secureString.AppendChar(c);
            }
            clientContext.Credentials = new SharePointOnlineCredentials(userName, secureString);           
        }

        /// <summary>
        /// 设置非online认证信息
        /// </summary>
        /// <param name="clientContext"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="domain"></param>
        public static void setClientCredential(ClientContext clientContext, string userName, string password, string domain)
        {
            clientContext.Credentials = new NetworkCredential(userName, password, domain);
        }

        /// <summary>
        /// 设置SSL认证信息
        /// </summary>
        /// <param name="clientContext"></param>
        /// <param name="cerPath"></param>
        public static void setClientCredentialSSL(ClientContext clientContext, string cerPath)
        {
            CerPath = cerPath;
            ServicePointManager.ServerCertificateValidationCallback = delegate(object sender1, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
            {
                bool validationResult = true;
                return validationResult;
            };

            ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(customXertificateValidation);
            clientContext.ExecutingWebRequest += new EventHandler<WebRequestEventArgs>(context_ExecutingWebRequest);

            clientContext.Credentials = CredentialCache.DefaultNetworkCredentials;

            //Submit the Request
            clientContext.ExecuteQuery();
        }

        /// <summary>
        /// 设置SSL认证信息
        /// </summary>
        /// <param name="clientContext"></param>
        /// <param name="cerPath"></param>
        public static void setClientCredentialSSL(string url, string cerPath)
        {
            ClientContext clientContext = new ClientContext(url);
            CerPath = cerPath;
            ServicePointManager.ServerCertificateValidationCallback = delegate(object sender1, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
            {
                bool validationResult = true;
                return validationResult;
            };

            ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(customXertificateValidation);
            clientContext.ExecutingWebRequest += new EventHandler<WebRequestEventArgs>(context_ExecutingWebRequest);

            clientContext.Credentials = CredentialCache.DefaultNetworkCredentials;
            //Submit the Request
            clientContext.ExecuteQuery();
        }

        public static void context_ExecutingWebRequest(object sender, WebRequestEventArgs e)
        {
            HttpWebRequest webReq = e.WebRequestExecutor.WebRequest;
            //webReq.Proxy = new WebProxy("http://[ProxyAddress]"); //Specify a proxy address if you need to
            X509Certificate cert = X509Certificate.CreateFromCertFile(CerPath);
            webReq.ClientCertificates.Add(cert);
        }

        public static bool customXertificateValidation(object sender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error)
        {
            return true;
        }

        public static string CerPath { get; set; }
        #endregion

        #region 获取用户在当前site下的权限集合
        /// <summary>
        /// 获取用户在当前site下的权限集合
        /// </summary>
        /// <param name="context"></param>
        public static List<PermissionKind> getAllUsersOfSite(ClientContext context, User user)
        {
            UserCollection userCollection = context.Web.SiteUsers;
            context.Load(userCollection);
            context.ExecuteQuery();
            List<PermissionKind> list = new List<PermissionKind>();

            string userName = user.LoginName;
            ClientResult<BasePermissions> permissions = context.Web.GetUserEffectivePermissions(user.LoginName);
            context.ExecuteQuery();
            foreach (PermissionKind permissionKind in Enum.GetValues(typeof(PermissionKind)))
            {
                string permisson = Enum.GetName(typeof(PermissionKind), permissionKind);
                bool hasPermisssion = permissions.Value.Has(permissionKind);
                if (hasPermisssion)
                {
                    list.Add(permissionKind);
                    //Console.WriteLine(permisson);
                }
            }
            return list;
        }
        #endregion
    }
}
